<template>
  <div class="view-fill">
    <div v-if="!modifyInfo.visible" class="app-container-flex">
      <full-screen
        v-model="showDialog"
        title="WMS入库单详情"
        :needOperateAffair="true"
        :operateAffairData="affairTableInfo"
        @returnBack="returnBack"
      >
        <template v-slot:full-button>
          <PopoverPrint
            ref="popoverShow"
            v-model:popoverVisible="popoverVisible"
            :canPrint="canPrint"
            :templateArr="templateArr"
            @tempClick="tempClick"
            @print="print"
          ></PopoverPrint>
          <!-- <el-button
            v-if="
              infoList.data.status !== 1 &&
              $permission('storageStock:printOrder')
            "
            @click="print"
            >打印</el-button
          > -->
          <el-button
            v-if="
              infoList.data.status !== 1 &&
              $permission('storageStock:excelOrder')
            "
            @click="exportExcel"
            >导出excel</el-button
          >
          <el-button v-if="canUpdate" @click="update">修改</el-button>
          <el-button v-if="canPrintQrCode" @click="pringQrCode"
            >打印二维码</el-button
          >
          <el-button v-if="canSubmit" @click="submit">提交</el-button>
          <el-button v-if="canRevoke" @click="revoke">撤回</el-button>
          <el-button v-if="canExecute" @click="wmsStore">入库</el-button>
          <el-button v-if="canQuickShelving" @click="quickShelving"
            >快捷上架</el-button
          >
          <el-button v-if="canPutShelf" @click="putShelf"
            >生成上架任务</el-button
          >
        </template>

        <div class="model-panel">
          <div class="model-panel-title">
            <p>{{ $t('basic_information') }}</p>
          </div>
          <div class="model-panel-body">
            <basic-information :info="infoList">
              <template v-slot:basic-invoiceNumber>
                <div
                  v-if="
                    infoList.data.invoiceNumberList &&
                    infoList.data.invoiceNumberList.length > 0
                  "
                >
                  <span
                    v-for="(item, index) in infoList.data.invoiceNumberList"
                    :key="index"
                  >
                    <a v-if="index <= 1">{{ item }}</a>
                    <span
                      v-if="
                        index < 1 && infoList.data.invoiceNumberList.length > 1
                      "
                      >,</span
                    >
                  </span>
                  <el-dropdown
                    v-if="infoList.data.invoiceNumberList.length > 2"
                  >
                    <span class="el-dropdown-link">
                      更多
                      <i class="el-icon-arrow-down el-icon--right"></i>
                    </span>
                    <template #dropdown>
                      <el-dropdown-menu>
                        <el-dropdown-item
                          v-for="(item, index) in infoList.data
                            .invoiceNumberList"
                          :key="index"
                          >{{ item }}</el-dropdown-item
                        >
                      </el-dropdown-menu>
                    </template>
                  </el-dropdown>
                </div>
                <span v-else>-</span>
              </template>
            </basic-information>
          </div>
        </div>

        <div class="model-panel">
          <div class="model-panel-title">
            <Tooltip :text="$t('detailInfo')" />
          </div>
          <div class="model-panel-body">
            <div class="flex_full_item">
              <!-- 表格 -->
              <page-table
                :refresh="tableInfo.refresh"
                :init-curpage="tableInfo.initCurpage"
                v-model:data="tableInfo.data"
                :pager="false"
                :summary="true"
                :check-box="false"
                :tab-index="true"
                :summary-field-list="tableInfo.summaryFieldList"
                :field-list="tableInfo.fieldList"
                :handle="tableInfo.handle"
                :isDynamic="true"
              >
              </page-table>
            </div>
          </div>
        </div>
      </full-screen>
    </div>
    <Modify
      v-if="modifyInfo.visible"
      v-model:visible="modifyInfo.visible"
      :title="modifyInfo.title"
      :order-id="modifyInfo.orderId"
      @returnModify="refreshDetail"
    />
    <chose-printer :visible="printerInfo.visible" @callBack="printerCallBack" />
    <individual-details
      v-if="individualInfo.visible"
      v-model:show-dialog="individualInfo.visible"
      :query="individualInfo.query"
      :info="individualInfo.info"
      :page-status="canPrintQrCode"
    />
    <!-- S 快捷上架弹窗 -->
    <PageDialog
      v-show="quickShelvingDialogInfo.visible"
      :title="quickShelvingDialogInfo.title"
      v-model:visible="quickShelvingDialogInfo.visible"
      :width="quickShelvingDialogInfo.width"
      :bt-loading="quickShelvingDialogInfo.btLoading"
      :bt-list="quickShelvingDialogInfo.btList"
    >
      <PageForm
        v-model:ref-obj="formInfo.ref"
        :data="formInfo.data"
        :field-list="formInfo.fieldList"
        :rules="formInfo.rules"
        :label-width="formInfo.labelWidth"
        :list-type-info="listTypeInfo"
      >
      </PageForm>
    </PageDialog>
    <!-- E 快捷上架弹窗 -->
    <!-- S 上架任务弹窗 -->
    <PageDialog
      v-show="putShelfDialogInfo.visible"
      :title="putShelfDialogInfo.title"
      v-model:visible="putShelfDialogInfo.visible"
      :width="putShelfDialogInfo.width"
      :bt-loading="putShelfDialogInfo.btLoading"
      :bt-list="putShelfDialogInfo.btList"
      @reset="putShelfClose"
    >
      <PageForm
        v-model:ref-obj="putShelfFormInfo.ref"
        :data="putShelfFormInfo.data"
        :field-list="putShelfFormInfo.fieldList"
        :rules="putShelfFormInfo.rules"
        :label-width="putShelfFormInfo.labelWidth"
        :list-type-info="listTypeInfo"
      >
      </PageForm>
    </PageDialog>
    <!-- E 上架任务弹窗 -->
  </div>
</template>

<script setup name="wmsStoreOrderDetail">
import { orderOpAffairAll } from '@/api/affair'
import Modify from './modify'
import IndividualDetails from './individualDetails'
import { getCustomizeSetting } from '@/api/customize'
import { fatchTemplateByCode } from '@/api/base'
import {
  detailWmsStoreStockOrder,
  executeWmsStoreOrder,
  exportExcelWmsStoreOrder,
  getWmsStoreStorePrint,
  getWsmStoreStockOrderDetailCustomizeList,
  revokeWmsStoreOrder,
  submitWsmStoreStockOrder,
  wmsStoreOrderDetailsPrintQrCodeVO,
  wmsStoreStorePrintQrCode,
  createPutShelfOrder,
  getTransitionLocationByDeport,
  quickPutShelf,
} from '@/api/wms'
import { getRrgUserAll } from '@/api/base.js'
import _ from 'lodash'
import { doPrint } from '@/utils/exportUtil.js'
import { selectByCodeAndDept } from '@/api/report.js'
import { updatePrintCount } from '@/api/mapping'
const { proxy } = getCurrentInstance()
const emits = defineEmits()

const props = defineProps(['visible', 'tableRow', 'tempCode'])

const infoList = reactive({
  data: {},
  fieldList: [
    { label: '入库单号', value: 'orderNo', type: 'text' },
    { label: '类型', value: 'typeValue', type: 'text' },
    { label: '入库仓库', value: 'depotName', type: 'text' },
    { label: '入库部门', value: 'deptName', type: 'text' },
    { label: '状态', value: 'statusValue', type: 'text' },
    { label: '入库人', value: 'storeUserName', type: 'text' },
    { label: '入库时间', value: 'storeTime', type: 'text' },
    { label: '创建人', value: 'createUserName', type: 'text' },
    { label: '创建时间', value: 'createTime', type: 'text' },
    { label: '更新人', value: 'updateUserName', type: 'text' },
    { label: '更新时间', value: 'updateTime', type: 'text' },
    {
      label: '是否寄售业务',
      value: 'isConsignBusinessValue',
      type: 'text',
      show: proxy.$store.state.permission.systemConfig.is_consign_business == 1,
    },
    { label: '备注', value: 'remark', type: 'text' },
  ],
})
// 过滤相关配置
const filterInfo = reactive({
  query: {
    customizeUserVO: {},
    queryMap: {
      orderId: {
        queryType: 'EQUALS',
        queryCategory: 'AND',
        value: props.tableRow.orderId || props.tableRow.id,
      },
    },
    queryParams: {},
  },
})
const modifyInfo = reactive({
  visible: false,
  title: '',
})
// 表格相关
const tableInfo = reactive({
  refresh: 1,
  initCurpage: 1,
  data: [],
  summaryFieldList: [
    { value: 'qty', formatter: proxy.$fn.qtyFormatter },
    { value: 'sumAmount', formatter: proxy.$fn.TripartiteMethod },
  ],
  fieldList: [],
  handle: {
    fixed: 'right',
    label: '操作',
    width: '150',
    btList: [
      {
        label: '打印二维码',
        event: printSingleQrCode,
        show: proxy.$permission('storageStock:printCode'),
        ifRender: ifRenderValue,
      },
      {
        label: '个体详情',
        event: showDetail,
        show: proxy.$permission('storageStock:IndividualDetails'),
      },
    ],
  },
})
const affairTableInfo = reactive({
  api: orderOpAffairAll,
  query: {
    orderType: 78,
    orderId: props.tableRow.orderId || props.tableRow.id,
    sort: 'operate_time desc',
  },
})
const individualInfo = reactive({
  visible: false,
  query: {},
  info: {},
})
const printerInfo = reactive({
  visible: false,
  data: {},
})
const listTypeInfo = reactive({
  transitionalCargoList: [],
  userList: [],
})
const quickShelvingDialogInfo = ref({
  visible: false,
  title: '请选择过渡货位',
  btLoading: false,
  type: '',
  msg: '',
  width: '400px',
  flag: true,
  btList: [
    { label: '取消', event: quickShelvingClose, show: true },
    {
      label: '确认',
      type: 'primary',
      event: quickShelvingConfirm,
      show: true,
    },
  ],
})
//表单相关
const formInfo = ref({
  ref: null,
  data: {},
  fieldList: [
    {
      label: '过渡货位',
      value: 'transition',
      type: 'select',
      list: 'transitionalCargoList',
      clearable: true,
      filterable: true,
    },
  ],
  rules: {
    transition: [
      {
        required: true,
        message: '请选择过渡货位',
        trigger: ['blur'],
      },
    ],
  },
  labelWidth: '100px',
})
const canPrint = computed(() => {
  return (
    proxy.$permission('storageStock:printOrder') && infoList.data.status !== 1
  )
})
// 快捷上架弹窗
function quickShelving() {
  quickShelvingDialogInfo.value.visible = true
  quickShelvingDialogInfo.value.id = props.tableRow.id
  proxy.$nextTick(() => {
    formInfo.value.ref.resetFields()
  })
  _getTransitionLocationByDeport(props.tableRow)
}
// 关闭快捷上架
function quickShelvingClose() {
  quickShelvingDialogInfo.value.visible = false
}
// 快捷上架过渡货位确认
function quickShelvingConfirm() {
  formInfo.value.ref.validate((valid) => {
    if (valid) {
      _quickPutShelf()
    }
  })
}
//获取计量单位列表
function _getTransitionLocationByDeport(row) {
  console.log(row)
  getTransitionLocationByDeport(row.depotId).then((resp) => {
    if (resp && resp.success && resp.data && resp.data.length > 0) {
      listTypeInfo.transitionalCargoList = resp.data.map(function (item) {
        return { key: item.locationNo, value: item.id }
      })
    }
  })
}
//快捷上架
function _quickPutShelf() {
  let params = {
    id: quickShelvingDialogInfo.value.id,
  }
  params = { ...params, ...formInfo.value.data }
  console.log(params)
  quickPutShelf(params).then((res) => {
    if (res && res.success) {
      quickShelvingDialogInfo.value.visible = false
      refreshDetail()
    }
  })
}

const putShelfDialogInfo = ref({
  visible: false,
  title: '请选择拆分类型及上架人',
  btLoading: false,
  type: '',
  msg: '',
  width: '400px',
  flag: true,
  btList: [
    { label: '取消', event: putShelfClose, show: true },
    {
      label: '确认',
      type: 'primary',
      event: putShelfConfirm,
      show: true,
    },
  ],
})
//表单相关
const putShelfFormInfo = ref({
  ref: null,
  data: { putShelfUser: -2 },
  fieldList: [
    {
      label: '任务拆分类型',
      value: 'putSplitType',
      type: 'select-model',
      code: 'wms_put_split_type',
      checkDefault: true,
      required: true,
    },
    {
      label: '选择上架人',
      value: 'putShelfUser',
      type: 'select',
      list: 'userList',
      checkDefault: true,
      filterable: true,
    },
  ],
  rules: {
    putSplitType: [
      {
        required: true,
        message: '请选择任务拆分类型',
        trigger: ['blur'],
      },
    ],
  },
  labelWidth: '120px',
})
watch(
  () => putShelfFormInfo.value.data,
  (val) => {
    // 任务拆分类型-按产品拆分
    if (val.putSplitType == '1') {
      putShelfFormInfo.value.fieldList =
        putShelfFormInfo.value.fieldList.filter((element) => {
          return element.value !== 'putShelfUser'
        })
      putShelfFormInfo.value.data['putShelfUser'] = -2
    } else {
      // 任务拆分类型-不拆分（可选择用户）
      putShelfFormInfo.value.fieldList = addItem(
        putShelfFormInfo.value.fieldList,
        {
          label: '选择用户',
          value: 'putShelfUser',
          type: 'select',
          list: 'userList',
          clearable: false,
          filterable: true,
        }
      )
    }
    console.log(val)
  },
  { deep: true }
)
// 防止添加数组重复项
function addItem(items, item) {
  let foundObject = _.find(items, (e) => {
    return e.value === item.value
  })

  if (!foundObject) {
    items.push(item)
  }
  return items
}
// 上架任务弹窗
function putShelf() {
  putShelfDialogInfo.value.visible = true
  putShelfDialogInfo.value.id = props.tableRow.id
}
// 关闭上架任务弹窗
function putShelfClose() {
  putShelfDialogInfo.value.visible = false
  proxy.$nextTick(() => {
    putShelfFormInfo.value.ref.resetFields()
  })
}
// 上架任务弹窗确认
function putShelfConfirm() {
  putShelfFormInfo.value.ref.validate((valid) => {
    if (valid) {
      savePutShelfUser()
    }
  })
}
function savePutShelfUser() {
  let params = {
    id: putShelfDialogInfo.value.id,
    ...putShelfFormInfo.value.data,
  }
  createPutShelfOrder(params).then((res) => {
    if (res && res.success) {
      putShelfDialogInfo.value.visible = false
      refreshDetail()
    }
  })
}
//获取人员列表
function getUserList() {
  let params = {
    sort: 'create_time desc',
    idNotIn: props.tableRow.putShelfUser || '',
    status: 1,
    isTransfer: 1,
    depotAuth: props.tableRow.depotId,
  }
  getRrgUserAll(params).then((res) => {
    if (res && res.success) {
      let arr = [{ key: '暂不选择', value: -2, userName: '' }]
      if (res.data && res.data.length) {
        let data = res.data.map((item) => {
          return {
            key: item.name,
            value: item.id,
            userName: item.userName,
          }
        })
        listTypeInfo.userList = arr.concat(data)
      }
    }
  })
}
getUserList()
const showDialog = computed({
  get() {
    return props.visible
  },
  set(newValue) {
    emits('update:visible', newValue) // 更新父组件visible
  },
})

const canUpdate = computed(() => {
  return proxy.$permission('storageStock:update') && infoList.data.status === 1
})
const canPrintQrCode = computed(() => {
  return (
    proxy.$permission('storageStock:printCode') &&
    (infoList.data.status === 2 ||
      infoList.data.status === 3 ||
      infoList.data.status === 4 ||
      infoList.data.status === 5)
  )
})

const canSubmit = computed(() => {
  return proxy.$permission('storageStock:submit') && infoList.data.status === 1
})
const canRevoke = computed(() => {
  return (
    proxy.$permission('storageStock:revoke') &&
    infoList.data.status === 2 &&
    infoList.data.sourceOrderId === -2
  )
})
const canExecute = computed(() => {
  return proxy.$permission('storageStock:store') && infoList.data.status === 2
})
const canQuickShelving = computed(() => {
  return (
    proxy.$permission('storageStock:quickPutShelf') &&
    infoList.data.status === 3
  )
})
const canPutShelf = computed(() => {
  return (
    proxy.$permission('storageStock:createPutShelf') &&
    infoList.data.status === 3
  )
})

watch(
  () => props.visible,
  (value) => {
    showDialog.value = value
  },
  {
    immediate: true,
  }
)
watch(
  () => props.tableRow,
  (newVal) => {
    if (newVal.id) {
      filterInfo.query.queryMap.orderId.value = newVal.orderId || newVal.id
      affairTableInfo.query.orderId = newVal.orderId || newVal.id
    }
    // refreshDetail()
  },
  {
    immediate: true,
    deep: true,
  }
)

let obj = {
  price: {
    label: '单价',
    value: 'price',
    formatter: proxy.$fn.TripartiteMethod,
    permission: !proxy.$permission('storageStock:price'),
    show: false,
    hidden: true,
  },
  sumAmount: {
    label: '总金额',
    value: 'sumAmount',
    formatter: proxy.$fn.TripartiteMethod,
    permission: !proxy.$permission('storageStock:price'),
    show: false,
    hidden: true,
  },
  orderNo: {
    label: '单号',
    value: 'orderNo',
    componentType: 'input',
    show: false,
    type: 'column',
    hidden: true,
  },
  defaultSupplierPrice: {
    label: '默认供应商价格',
    value: 'defaultSupplierPrice',
    type: 'column',
    permission: !proxy.$permission('storageStock:price'),
    formatter: proxy.$fn.TripartiteMethod,
    hidden: true,
  },
  locationTypeValue: {
    label: '货位属性',
    value: 'locationTypeValue',
    asValue: 'locationType',
    componentType: 'select-model',
    code: 'goods_location_type',
    show: false,
    hidden: true,
  },
}
tableInfo.fieldList = Object.values({
  ...proxy.$fn.deepClone(proxy.$fieldfList.FieldList),
  ...obj,
})
getCustomize()

//提交
function submit() {
  let ids = []
  ids.push(infoList.data.id)
  submitWsmStoreStockOrder(ids).then((resp) => {
    if (resp && resp.success) {
      refreshDetail()
    }
  })
}
function revoke() {
  let ids = []
  ids.push(infoList.data.id)
  revokeWmsStoreOrder(ids).then((resp) => {
    if (resp && resp.success) {
      refreshDetail()
    }
  })
}
function wmsStore() {
  executeWmsStoreOrder(infoList.data.id).then((resp) => {
    if (resp && resp.success) {
      refreshDetail()
    }
  })
}
function refreshDetail() {
  getMain()
  getList()
}
function returnBack() {
  showDialog.value = false
  emits('returnBack', false)
}
function showDetail(row) {
  let ids
  if (row.groupConcatIds) {
    //未定义表示没有分组条件
    ids = row.groupConcatIds
  } else {
    ids = '' + row.id
  }
  individualInfo.query = {
    id: {
      queryType: 'IN',
      queryCategory: 'AND',
      value: ids,
    },
    orderId: {
      queryType: 'EQUALS',
      queryCategory: 'AND',
      value: props.tableRow.orderId || props.tableRow.id,
    },
  }
  individualInfo.info = row
  individualInfo.visible = true
}
function getMain() {
  detailWmsStoreStockOrder(props.tableRow.orderId || props.tableRow.id).then(
    (resp) => {
      if (resp && resp.success) {
        infoList.data = resp.data
        infoList.data.invoiceNumberList = infoList.data.invoiceNumber
          ? infoList.data.invoiceNumber.indexOf(',') !== -1
            ? infoList.data.invoiceNumber.split(',')
            : [infoList.data.invoiceNumber]
          : []
      }
    }
  )
}
function ifRenderValue() {
  return (
    infoList.data.status === 2 ||
    infoList.data.status === 3 ||
    infoList.data.status === 4 ||
    infoList.data.status === 5
  )
}
function update() {
  modifyInfo.orderId = infoList.data.id
  modifyInfo.title = '修改入库单'
  modifyInfo.visible = true
}
function getList() {
  getWsmStoreStockOrderDetailCustomizeList(filterInfo.query).then((resp) => {
    if (resp && resp.success) {
      tableInfo.data = resp.data
    }
  })
}
const templateArr = ref([])
const popoverVisible = ref(false)
// 打印
// 异常上架任务和wms入库单都使用的这个详情组件（通过是否传递 props.tempCode判断） 异常上架任务-传递了tempCode
function print() {
  selectByCodeAndDept({
    tempCode: props.tempCode || 'wmsStoreDetail',
    deptId: infoList.data.deptId,
  }).then((res) => {
    if (res && res.success) {
      templateArr.value = res.data
      popoverVisible.value = true
      // 一条数据则直接打印
      if (templateArr.value.length === 1) {
        proxy.$refs.popoverShow.hidePopover()
        doPrint({
          name: templateArr.value[0].ureportName,
          params: {
            orderId: props.tempCode
              ? props.tableRow.orderId
              : props.tableRow.id,
          },
          callback: printCallback,
          data: {},
        })
      }
    }
  })
}
function printCallback() {
  try {
    // 打印成功增加打印次数
    updatePrintCount({
      orderNo: infoList.data.orderNo,
      orderId: props.tempCode ? props.tableRow.orderId : props.tableRow.id,
      orderType: 78,
    })
  } catch (error) {}
}
function tempClick(item) {
  doPrint({
    name: item.ureportName,
    params: {
      orderId: props.tempCode ? props.tableRow.orderId : props.tableRow.id,
    },
    callback: printCallback,
    data: {},
  })
  popoverVisible.value = false
}
function getPrintData(temp) {
  let params = {
    tableKey:
      'wmsStoreStockOrderDetail-com.slip.spd.entity.vo.wms.WmsStoreStockOrderDetailVO',
    orderIds: [props.tableRow.orderId || props.tableRow.id],
  }
  getWmsStoreStorePrint(params).then((res) => {
    if (res.success && res) {
      let data = proxy.$fn.deepClone(res.data)
      let newData = data.map((item) => {
        return {
          ...item,
          ...item.orderInfo,
        }
      })
      proxy.$lodop.preview(
        temp,
        newData,
        !proxy.$permission('storageStock:price')
      )
    }
  })
}
//导出excel
function exportExcel() {
  exportExcelWmsStoreOrder(filterInfo.query).then((resp) => {
    if (resp) {
      proxy.$fn.parseExcel(resp)
    }
  })
}
//打印单个二维码
function printSingleQrCode(row = undefined) {
  if (!row.qrCode) {
    proxy.$message({
      message: '没有生成二维码，不能打印',
      type: 'warning',
      duration: 3500,
      showClose: true,
    })
    return
  }

  let ids
  if (row.groupConcatIds) {
    //未定义表示没有分组条件
    ids = proxy.$fn.splitArr(row.groupConcatIds)
  } else {
    ids = [row.id]
  }
  if (ids.length > 0) {
    wmsStoreOrderDetailsPrintQrCodeVO(ids).then((resp) => {
      if (resp && resp.success) {
        printerInfo.visible = true
        printerInfo.data = resp.data
      }
    })
  }
}
//打印整单的二维码
function pringQrCode() {
  let ids = []
  ids.push(props.tableRow.orderId || props.tableRow.id)
  if (ids.length > 0) {
    wmsStoreStorePrintQrCode(ids).then((resp) => {
      if (resp && resp.success) {
        printerInfo.visible = true
        printerInfo.data = resp.data
      }
    })
  }
}
function printerCallBack(printer) {
  if (printer !== false) {
    proxy.$print.buildRenderBarCode(printerInfo.data, printer)
  }
  printerInfo.visible = false
}
function getCustomize() {
  let param = {
    tableKey:
      'wmsStoreStockOrderDetail-com.slip.spd.entity.vo.wms.WmsStoreStockOrderDetailVO',
  }
  getCustomizeSetting(param).then((res) => {
    if (res && res.success) {
      let data = res.data
      filterInfo.query.customizeUserVO = data
      let obj = proxy.$fn.setFieldList(tableInfo.fieldList, data.detail, true)
      tableInfo.fieldList = obj.fieldList
      getMain()
      getList()
    }
  })
}
</script>

<style scoped></style>
